/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "fr_local.h"
#include "gl_local.h"

/*-----------------------------------------------------------------------------
	forward rendering stuff :
-----------------------------------------------------------------------------*/


//
//	EFRScene::RenderScene
//
void EFRScene::RenderScene( void )
{
	IPxVar	fr_stereo_factor;
	CONFIG_REGISTER_VAR( fr_stereo_factor, 1.0f );

	uint w, h;
	driver->GetScreenSize(w, h);
	IPxTexture	color	=	rtm->AllocRenderTarget( RS_FORMAT_ARGB_U8,			w, h );
	IPxTexture	depth	=	rtm->AllocRenderTarget( RS_FORMAT_DEPTH_READABLE,	w, h );

	if (!driver->CheckFeature( RS_FEATURE_STEREO )) {
	
		RenderSceneInternal( color, depth, 0 );
		rtm->CopyColorToBackBuffer( color, true, true, false );
		
	} else {
		float		factor	=	fr_stereo_factor->Float();
		EVector		offset	=	EVector(factor/2.0f,0,0).Transform( view.matrix_view.Inverse() );
		
		EPoint		vp	=	view.position;
		EMatrix	vm	=	view.matrix_view;
		EMatrix	vml	=	vm * EMatrix::Translate(  factor, 0, 0 );
		EMatrix	vmr	=	vm * EMatrix::Translate( -factor, 0, 0 );

		//	left :
		view.position		+=	offset;
		view.matrix_view	=	vmr;
		RenderSceneInternal( color, depth, 0 );
		rtm->CopyColorToBackBuffer( color, false, true, false );
		
		//	right :
		view.position		-=	offset;
		view.matrix_view	=	vml;
		RenderSceneInternal( color, depth, 1 );
		rtm->CopyColorToBackBuffer( color, true, false, false );

	}

	//static bool first = true;
	//if (first)
	//{
	//	AddVolume();
	//	//volume->LoadFromCube("volume/9960.cube"); // 9960
	//	volume->LoadColormap("volume/blue-red.png");

	//	volume->SetBounds(EBBox(EPoint(), 20, 20, 20));
	//	volume->SetResolution(64, 64, 64);
	//	volume->SetInterestRange(-5.0, 5.0);
	//	first = false;

	//}
	//else
	//{
	//	struct Provider : public IFRVolume::DataProvider
	//	{
	//		float time;
	//		float shift;
	//		Provider(float t) : time(t)
	//		{
	//			shift = 0.5*sin(t);
	//		}

	//		static float Max(float a, float b)
	//		{
	//			return (a > b) ? a : b;
	//		}


	//		virtual float Value(const EPoint & p) const
	//		{
	//			return p.x;
	//			float value = 0;
	//			float x = 3*cos(time);
	//			float y = 3*sin(time);

	//			value += (2 / (0.1 + EMath::Sqr(EVector(p, EPoint( x, y,0)).Length())));
	//			value += (2 / (0.1 + EMath::Sqr(EVector(p, EPoint( 0, 0,1)).Length())));
	//			value -= (2 / (0.1 + EMath::Sqr(EVector(p, EPoint(-x,-y,0)).Length())));

	//			return value;

	//			/*//EPoint ps[3] = {
	//			//	EPoint(1,1,1),
	//			//	EPoint(1,5,1),
	//			//	EPoint(4,2,3),
	//			//};



	//			float value = 0;
	//			for (uint i=1; i<4; i++) {
	//				EPoint ps(	sin(i*sys()->Milliseconds()/1000.0f),
	//							sin(i*sys()->Milliseconds()/700.0f),
	//							sin(i*sys()->Milliseconds()/900.0f) );
	//							
	//				value += 100 / (1+ EMath::Sqr( EVector(p, ps).Length()) );
	//			}
	//			return value;

	//			//return p.x + p.y + p.z;
	//			//float v = Max( Max( abs(p.x), abs(p.y) ), abs(p.z));
	//			//return v+shift + sin(p.x*0.2+time) + sin(p.y*0.3+0.5*time) + sin(p.z*0.4+0.5*time);*/
	//			/*float x = p.x, y = p.y, z = p.z + 8;
	//			float d2 = x*x + y*y;
	//			float d = sqrt(d2);
	//			float phi = atan2(y, x) + sin(d - 2.0*time)*0.4;
	//			z -= d2*0.2;
	//			float v = sqrt(d2 + z*z*25);
	//			return v*(1.0 + sin(phi*5)*0.5);*/


	//		}
	//	};

	//	Provider prov(common.time);
	//	volume->UpdateData(&prov);

	//}

	rtm->ResetFrameBuffer();
}


//
//	EFRScene::RenderSceneInternal
//
void EFRScene::RenderSceneInternal( IPxTexture color, IPxTexture depth, int subframe )
{
	common.random	=	EMath::Randf();;
	common.time		=	System()->Milliseconds() / 1000.0f;
	
	uint w, h;
	driver->GetScreenSize(w, h);

	EFrame		frame;
	frame.color			=	color;
	frame.depth			=	depth;
	EGBuffer	gbuf;
	gbuf.clr[0]			=	rtm->AllocRenderTarget( RS_FORMAT_ARGB_U8,			w, h );
	gbuf.clr[1]			=	rtm->AllocRenderTarget( RS_FORMAT_ARGB_U8,			w, h );
	gbuf.clr[2]			=	rtm->AllocRenderTarget( RS_FORMAT_ARGB_U8,			w, h );
	gbuf.ds				=	rtm->AllocRenderTarget( RS_FORMAT_DEPTH_READABLE,	w, h );
	
	rtm->SetFrameBuffer( depth, color );
	rtm->ClearFrameBuffer( RS_CLEAR_STENCIL | RS_CLEAR_DEPTH, EColor(0,0,0,0) );

	RenderSolid( gbuf );		//	put all solid geometry stuff to g-buffer.
		
	RenderLighting( gbuf, frame.color, frame.depth );		//	compute lighting for current g-buffer.
	
	RenderTranslucent();		//	render translucent stuff.
	
	RenderEmission();			//	render emissive stuff.
	
	//RenderSolid();
	
	//RenderDistortion();
	
	if (water) {
		water->Render( frame, gbuf );
	}

	if (volume)	{
		volume->Render( depth );
	}
	
	gfxsys->RenderGFXs();
	
	RenderWireframe();		//	render wireframe for debugging.

	if (!driver->CheckFeature( RS_FEATURE_STEREO )) {
		RenderMlaa( color, depth );
	}
	
	scrfx->RenderScreenFX(color);

	RenderSsao(depth, gbuf.clr[1], color);
}


//
//	EFRScene::RenderShadowMap
//
void EFRScene::RenderShadowMap( IPxTexture shadow_map, const EMatrix &view, const EMatrix &proj )
{
	EMatrix	view_matrix_view	=	this->view.matrix_view;
	EMatrix	view_matrix_proj	=	this->proj.matrix_proj;
	
	this->view.matrix_view	=	view;
	this->proj.matrix_proj	=	proj;
	
	RenderShadowMap( shadow_map );

	this->view.matrix_view	=	view_matrix_view;
	this->proj.matrix_proj	=	view_matrix_proj;
}


//
//	EFRScene::RenderShadowMap
//
void EFRScene::RenderShadowMap( IPxTexture shadow_map )
{
	rtm->SetFrameBuffer( shadow_map, NULL );
	rtm->ClearFrameBuffer( RS_CLEAR_DEPTH, EColor(0,0,0,0) );

	sshs->SetTechnique( FR_TECH_SHADOWS );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}

	rtm->ResetFrameBuffer();
}


//
//	EFRScene::RenderSolid
//
void EFRScene::RenderSolid( EGBuffer &gbuf )
{
	rtm->SetFrameBuffer( gbuf.ds, gbuf.clr[0], gbuf.clr[1], gbuf.clr[2], NULL );
	rtm->ClearFrameBuffer( RS_CLEAR_DEPTH | RS_CLEAR_COLOR, EColor(0,0,0,0) );

	sshs->SetTechnique( FR_TECH_SOLID );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}

	rtm->ResetFrameBuffer();
}


//
//	EFRScene::RenderLighting
//
void EFRScene::RenderLighting( EGBuffer &gbuf, IPxTexture color, IPxTexture depth )
{
	lits->RenderLighting( gbuf, color, depth );
}


//
//	EFRScene::RenderTranslucent
//
void EFRScene::RenderTranslucent( void )
{
	sshs->SetTechnique( FR_TECH_TRANSLUCENT );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}
}


//
//	EFRScene::RenderEmission
//
void EFRScene::RenderEmission( void )
{
	sshs->SetTechnique( FR_TECH_EMISSIVE );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}
}


//
//	EFRScene::RenderDistortion
//
void EFRScene::RenderDistortion( void )
{
	sshs->SetTechnique( FR_TECH_DISTORTIVE );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}
}


//
//	EFRScene::RenderWireframe
//
void EFRScene::RenderWireframe( void )
{
	if (!fr_wireframe->Bool()) {
		return;
	}

	sshs->SetTechnique( FR_TECH_WIREFRAME );

	for (uint i=0; i<entities.size(); i++) {
		if (entities[i]) {
			entities[i]->Render();
		}
	}
}


//
//	EFRScene::RenderMlaa
//
void EFRScene::RenderMlaa( IPxTexture color, IPxTexture depth )
{
	mlaa->RenderMlaa( color, depth );
}


//
//	EFRScene::RenderSsao
//
void EFRScene::RenderSsao( IPxTexture depth, IPxTexture normal, IPxTexture color )
{
	ssao->RenderSsao( depth, normal, color );
}

/*-----------------------------------------------------------------------------
	Water rendering :
-----------------------------------------------------------------------------*/
